package org.cainiao.portal.controller.client.user;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.cainiao.acl.core.annotation.CnACL;
import org.cainiao.portal.dto.response.User;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录用户信息
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "User", description = "登录用户信息")
public class UserController {

    /**
     * URI 不能用 login，否则会进入到 Spring Security 的特殊端点
     *
     * @param authentication OAuth2AuthenticationToken
     * @return User
     */
    @CnACL(scopes = {"lark"})
    @GetMapping("user-login")
    @Operation(summary = "登录用户信息")
    public User login(OAuth2AuthenticationToken authentication) {
        return User.builder().userName(authentication.getName()).build();
    }

    @GetMapping("user")
    @Operation(summary = "登录用户信息")
    public User currentUser(@AuthenticationPrincipal AuthenticatedPrincipal principal) {
        return principal instanceof DefaultOidcUser oidcUser
            ? User.builder().userName(oidcUser.getUserInfo().getFullName()).build() : User.anonymousUser();
    }
}
